package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

public class Solicitud extends javax.swing.JInternalFrame {
    private String id_bitacora;
    private JFileChooser selector;
    public Solicitud() {
        initComponents();
        this.setLocation(new Point(70, 0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("solicitud.xls"));
        CargarSolicitantes();
        CargarAreas();
        Limpiar();
        Util.OcultarColumna(jtblResumenProducto, 0);
        Util.OcultarColumna(jtblResumenProducto, 2);
        Util.AlinearColumnas(jtblResumenProducto,SwingConstants.CENTER);
        Util.EstablecerEliminadorFila(jtblResumenProducto);
        if(Conexion.bitacora) id_bitacora=Util.IniciarBitacora(this.getTitle());
    }

    private void CargarSolicitantes() {
        jcbSolicitante.removeAllItems();
        String columnas[] = {"id", "nombres", "apellidos"};
        Util.CargarJComboBox(jcbSolicitante, "SELECT id_solicitante,nombres,apellidos FROM solicitante", columnas);
    }

    private void CargarAreas() {
        jcbAreas.removeAllItems();
        String columnas[] = {"id", "nombre"};
        Util.CargarJComboBox(jcbAreas, "SELECT id_area,nombre FROM area", columnas);
    }

    private void CargarProductosDetallados(String texto) {
        DefaultListModel<ModeloItemValor> modelo = new DefaultListModel<ModeloItemValor>();
        jlbDetalleProducto.setModel(modelo);
        modelo.removeAllElements();
        String columnas[] = {"id", "descripcion"};
        JTable tabla = Conexion.ObtenerTabla("SELECT i.id_inventario,CONCAT_WS(' ',p.nombre,i.unidad_medida,i.detalle) AS descripcion FROM inventario i "
                + "INNER JOIN producto p ON i.id_producto=p.id_producto WHERE p.nombre LIKE '"+Util.ComponerTexto(texto)+"%'", columnas);
        for (int i = 0; i < tabla.getRowCount(); i++)
            modelo.addElement(new ModeloItemValor(tabla.getValueAt(i, 1).toString(), tabla.getValueAt(i, 0).toString()));
    }
    private void CargarDetallesTabla(String id_inventario) {
        Util.CargarTablaEditable(jtblProductos,"SELECT i.id_inventario,concat_ws(' ',p.nombre,i.unidad_medida,i.detalle),b.id_bodega,b.nombre,"
                +"ib.cantidad,(CASE WHEN DATE_FORMAT(ib.fecha_vencimiento,'%d/%m/%Y')='31/12/9999' THEN '-' ELSE DATE_FORMAT(ib.fecha_vencimiento,"
                +"'%d/%m/%Y') END) AS fecha,(CASE WHEN p.es_devolutivo='S' THEN 'Si' ELSE 'No' END),0 as cantidad FROM Inventario i INNER JOIN Producto p "
                +"ON i.id_producto=p.id_producto INNER JOIN Inventario_Bodega ib ON i.id_inventario=ib.id_inventario INNER JOIN Bodega b "
                +"ON ib.id_bodega=b.id_bodega WHERE i.id_inventario="+id_inventario+";",
                new String []{"id","Producto","ID_Bodega","Bodega","Cantidad","Fecha Vencimiento","Devolutivo","Cantidad Solicitada"},
                new boolean[]{false, false, false, false, false, false, false, true});
        Util.OcultarColumna(jtblProductos, 0);
        Util.OcultarColumna(jtblProductos, 2);
        Util.AlinearColumnas(jtblProductos,SwingConstants.CENTER);
    }
    private void Limpiar() {
        jtfNombreProducto.setText(null);
        jtaObservacion.setText(null);
        jlbDetalleProducto.removeAll();
        jcbSolicitante.setSelectedIndex(-1);
        jcbAreas.setSelectedIndex(-1);
        CargarDetallesTabla("-1");
        jlNumSolicitud.setText("");
        while (jtblResumenProducto.getRowCount() > 0)
            ((DefaultTableModel) jtblResumenProducto.getModel()).removeRow(0);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpSolicitante = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jcbSolicitante = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jcbAreas = new javax.swing.JComboBox();
        jtfNombreProducto = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlbDetalleProducto = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        jpProductosDisponibles = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jtblProductos = new javax.swing.JTable();
        jbtnAgregar = new javax.swing.JButton();
        jpDetalles = new javax.swing.JPanel();
        jbtnGuardar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane6 = new javax.swing.JScrollPane();
        jtblResumenProducto = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtaObservacion = new javax.swing.JTextArea();
        jlNumSolicitud = new javax.swing.JLabel();
        jbtnExportar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Soliitudes");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/solicitud.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jLabel1.setText("Solicitante");

        jLabel2.setText("Area");

        jtfNombreProducto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfNombreProductoKeyPressed(evt);
            }
        });

        jLabel3.setText("Producto");

        jlbDetalleProducto.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jlbDetalleProductoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jlbDetalleProducto);

        jLabel4.setText("Productos Disponibles");

        jpProductosDisponibles.setBorder(javax.swing.BorderFactory.createTitledBorder("Productos Disponibles"));

        jtblProductos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Bodega", "Existencia", "Fecha Vencimiento", "Devolutivo", "Cantidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane4.setViewportView(jtblProductos);

        javax.swing.GroupLayout jpProductosDisponiblesLayout = new javax.swing.GroupLayout(jpProductosDisponibles);
        jpProductosDisponibles.setLayout(jpProductosDisponiblesLayout);
        jpProductosDisponiblesLayout.setHorizontalGroup(
            jpProductosDisponiblesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpProductosDisponiblesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4)
                .addContainerGap())
        );
        jpProductosDisponiblesLayout.setVerticalGroup(
            jpProductosDisponiblesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpProductosDisponiblesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(13, Short.MAX_VALUE))
        );

        jbtnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_nuevo.png"))); // NOI18N
        jbtnAgregar.setToolTipText("Nuevo");
        jbtnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAgregarActionPerformed(evt);
            }
        });

        jpDetalles.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle Solicitud"));

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.setToolTipText("Guardar");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        jLabel5.setText("Observaciones");

        jtblResumenProducto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id_inventario", "Producto", "id_bodega", "Bodega", "Fecha Vencimiento", "Devolutivo", "Cantidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Long.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane6.setViewportView(jtblResumenProducto);

        jtaObservacion.setColumns(20);
        jtaObservacion.setRows(5);
        jScrollPane2.setViewportView(jtaObservacion);

        javax.swing.GroupLayout jpDetallesLayout = new javax.swing.GroupLayout(jpDetalles);
        jpDetalles.setLayout(jpDetallesLayout);
        jpDetallesLayout.setHorizontalGroup(
            jpDetallesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDetallesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpDetallesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpDetallesLayout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2)
                        .addGap(18, 18, 18)
                        .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpDetallesLayout.createSequentialGroup()
                        .addComponent(jScrollPane6)
                        .addContainerGap())))
        );
        jpDetallesLayout.setVerticalGroup(
            jpDetallesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDetallesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpDetallesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnGuardar)
                    .addComponent(jLabel5)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jlNumSolicitud.setText("N° Solicitud:");

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpSolicitanteLayout = new javax.swing.GroupLayout(jpSolicitante);
        jpSolicitante.setLayout(jpSolicitanteLayout);
        jpSolicitanteLayout.setHorizontalGroup(
            jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpSolicitanteLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpSolicitanteLayout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jcbSolicitante, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jcbAreas, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jtfNombreProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpSolicitanteLayout.createSequentialGroup()
                                .addGap(139, 139, 139)
                                .addComponent(jLabel4))
                            .addGroup(jpSolicitanteLayout.createSequentialGroup()
                                .addGap(50, 50, 50)
                                .addComponent(jlNumSolicitud)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jpProductosDisponibles, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpDetalles, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(jpSolicitanteLayout.createSequentialGroup()
                .addGap(215, 215, 215)
                .addComponent(jbtnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(228, 228, 228))
        );
        jpSolicitanteLayout.setVerticalGroup(
            jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpSolicitanteLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jpSolicitanteLayout.createSequentialGroup()
                        .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jcbSolicitante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jcbAreas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlNumSolicitud))
                        .addGap(18, 18, 18)
                        .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jtfNombreProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addGap(1, 1, 1)
                .addComponent(jpProductosDisponibles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpDetalles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jpProductosDisponibles.getAccessibleContext().setAccessibleName("Detalle Solicitud");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpSolicitante, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpSolicitante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 36, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jbtnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAgregarActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) jtblResumenProducto.getModel();
        if(VerificarCantidadesNegativas()){
            for (int i = 0; i < jtblProductos.getRowCount(); i++) {
                long existencia=new Long(jtblProductos.getValueAt(i, 4).toString());
                long cantidad=new Long(jtblProductos.getValueAt(i, 7).toString());
                if (cantidad > 0) {
                    if(cantidad<=existencia){
                        int pos=PosicionExistencia((int)jtblProductos.getValueAt(i,0),(int)jtblProductos.getValueAt(i,2),jtblProductos.getValueAt(i,5).toString());
                        if(pos!=-1){
                            long valor=(long)jtblResumenProducto.getValueAt(pos,6)+(long)cantidad;
                            jtblResumenProducto.setValueAt(valor,pos,6);
                        }
                        else{
                            Object fila[] = new Object[7];
                            fila[0] = jtblProductos.getValueAt(i, 0);
                            fila[1] = jtblProductos.getValueAt(i, 1);
                            fila[2] = jtblProductos.getValueAt(i, 2);
                            fila[3] = jtblProductos.getValueAt(i, 3);
                            fila[4] = jtblProductos.getValueAt(i, 5);
                            fila[5] = jtblProductos.getValueAt(i, 6);
                            fila[6] = jtblProductos.getValueAt(i, 7);
                            modelo.addRow(fila);
                        }
                        if(existencia==cantidad)
                            ((MyModeloTablaEditable)jtblProductos.getModel()).EliminarFila(i);
                        else{
                            jtblProductos.setValueAt(existencia-cantidad,i,4);
                            jtblProductos.setValueAt(0,i,7);
                        }
                    }
                    else
                        JOptionPane.showMessageDialog(null,"La cantidad debe ser menor o igual que la existencia","Cantidad sobre pasa la Existencia", JOptionPane.WARNING_MESSAGE);
                }
            }
        }
        else
            JOptionPane.showMessageDialog(null,"La cantidad debe ser mayor que cero.","Cantidad Negativa", JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnAgregarActionPerformed
    private boolean VerificarCantidadesNegativas(){
        for (int i = 0; i < jtblProductos.getRowCount(); i++)
            if(new Integer(jtblProductos.getValueAt(i,7).toString())<0)
                return false;
        return true;
    }
    private int PosicionExistencia(int inventario,int bodega,String fecha){
        for(int i=0;i<jtblResumenProducto.getRowCount();i++){
            int inven=(int)jtblResumenProducto.getValueAt(i,0);
            int bod=(int)jtblResumenProducto.getValueAt(i,2);
            String fexa=jtblResumenProducto.getValueAt(i,4).toString();
            if(inventario==inven && bodega==bod && fecha.equals(fexa))
                return i;
        }
        return -1;
    }
    private void Guardar() {
        SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
        String[] detalle = detalleProducto();
        int area = Integer.parseInt(((ModeloItemValor)jcbAreas.getSelectedItem()).getValor());
        int solicitante = Integer.parseInt(((ModeloItemValor)jcbSolicitante.getSelectedItem()).getValor());
        if (Conexion.EjecutarProcedimientoAlmacenado("CALL AgregarSolicitud("+area+","+solicitante+",'" +formato.format(new Date())+"','"
                +Util.ComponerTexto(jtaObservacion.getText())+"','"+detalle[0]+"','"+detalle[1]+"','"+detalle[2]+"','"+detalle[3]+"')")){
                        jlNumSolicitud.setText("N° Solicitud: "+Conexion.ObtenerTabla("SELECT MAX(id_solicitud) FROM solicitud",new String[]{"id"}).getValueAt(0,0).toString());
                        if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Solicitud Guardada: "+Util.ComponerTexto(jlNumSolicitud.getText()));
                        JOptionPane.showMessageDialog(null, "Solicitud Creada!", "Solicitud", JOptionPane.INFORMATION_MESSAGE);
                        Limpiar();
        }
        else
            JOptionPane.showMessageDialog(null, "No se pudo crear la solicitud!", "Error", JOptionPane.ERROR_MESSAGE);
    }
    private boolean verificarCantidades() {
        for (int i = 0; i < jtblResumenProducto.getRowCount(); i++)
            if (new Integer(jtblResumenProducto.getValueAt(i, 6).toString()) < 0)
                return false;
        return true;
    }
    private String[] detalleProducto() {
        String[] detalle = {"", "", "", ""};
        ArrayList<detallesolicitud> total_s = new ArrayList<detallesolicitud>();
        total_s.removeAll(total_s);
        int inventario,bodega;
        String fecha_vencimiento;
        SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
        for (int i = 0; i < jtblResumenProducto.getRowCount(); i++) {
            inventario = new Integer(jtblResumenProducto.getValueAt(i, 0).toString());
            
            String f=jtblResumenProducto.getValueAt(i, 4).toString();
            fecha_vencimiento = formato.format(new Date(f.equals("-") ? "9999/12/31" : f.substring(6)+"/"+f.substring(3,5)+"/"+f.substring(0,2)));
            bodega = new Integer(jtblResumenProducto.getValueAt(i, 2).toString());
            
            total_s.add(new Solicitud.detallesolicitud(inventario, bodega, new Integer(jtblResumenProducto.getValueAt(i, 6).toString()),fecha_vencimiento));
        }
        for (int i = 0; i < total_s.size(); i++) {
            if (i == total_s.size() - 1) {
                detalle[0] += total_s.get(i).dato1;
                detalle[1] += total_s.get(i).dato2;
                detalle[2] += total_s.get(i).dato3;
                detalle[3] += total_s.get(i).dato4;
            } else {
                detalle[0] += total_s.get(i).dato1 + ",";
                detalle[1] += total_s.get(i).dato2 + ",";
                detalle[2] += total_s.get(i).dato3 + ",";
                detalle[3] += total_s.get(i).dato4 + ",";
            }
        }
        return detalle;
    }

    private class detallesolicitud {
        public int dato1, dato2, dato3;
        public String dato4;
        public detallesolicitud(int dato1, int dato2, int dato3, String dato4) {
            this.dato1 = dato1;
            this.dato2 = dato2;
            this.dato3 = dato3;
            this.dato4 = dato4;
        }
    }
    private void jlbDetalleProductoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jlbDetalleProductoMouseClicked
        if (evt.getClickCount() == 2 && !evt.isConsumed() && jlbDetalleProducto.getSelectedIndex() > -1) {
            String id_inventario = ((ModeloItemValor) jlbDetalleProducto.getSelectedValue()).getValor();
            CargarDetallesTabla(id_inventario);
            RestarActuales();
        }
    }//GEN-LAST:event_jlbDetalleProductoMouseClicked
    private void RestarActuales(){
        for(int i=0;i<jtblResumenProducto.getRowCount();i++){
            int inventario=(int)jtblResumenProducto.getValueAt(i,0);
            int bodega=(int)jtblResumenProducto.getValueAt(i,2);
            long cantidad=(long)jtblResumenProducto.getValueAt(i,6);
            String fecha=jtblResumenProducto.getValueAt(i,4).toString();
            for(int j=0;j<jtblProductos.getRowCount();j++){
                int inven=(int)jtblProductos.getValueAt(j,0);
                int bod=(int)jtblProductos.getValueAt(j,2);
                int can=(int)jtblProductos.getValueAt(j,4);
                String fexa=jtblProductos.getValueAt(j,5).toString();
                if(inventario==inven && bodega==bod && fecha.equals(fexa)){
                    if(can-cantidad==0)
                        ((MyModeloTablaEditable)jtblProductos.getModel()).EliminarFila(j);
                    else
                        jtblProductos.setValueAt(can-cantidad,j,4);
                    break;
                }
            }
        }
    }
    private void Buscar(String texto) {
        if (jcbSolicitante.getSelectedIndex() > -1 && jcbAreas.getSelectedIndex() > -1) {
            jtfNombreProducto.setEditable(true);
            CargarProductosDetallados(texto);
        } else {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un solicitante y un area");
            Limpiar();
        }
    }
    private void jtfNombreProductoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNombreProductoKeyPressed
        if ((jtfNombreProducto.getText() + evt.getKeyChar()).trim().length() > 0) {
            Buscar((jtfNombreProducto.getText() + evt.getKeyChar()).trim());
        }
    }//GEN-LAST:event_jtfNombreProductoKeyPressed
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        if (jtblResumenProducto.getRowCount() > 0) {
            if(verificarCantidades())
                Guardar();
            else
                JOptionPane.showMessageDialog(null,"Las cantidades no deben tener valores negativos","Solicitud",JOptionPane.WARNING_MESSAGE);
        } else
            JOptionPane.showMessageDialog(null,"Debe agregar al menos un producto","Solicitud",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        if(Conexion.bitacora) Util.ClausurarBitacora(id_bitacora);
    }//GEN-LAST:event_formInternalFrameClosing

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblResumenProducto.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarExcel(jtblResumenProducto,archivo_excel,"Solicitud")){
                        case OK:
                            JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                            Desktop.getDesktop().open(archivo_excel);
                            break;
                        case CANCELADO:
                            break;
                        case ERROR:
                            JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                            break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JButton jbtnAgregar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JComboBox jcbAreas;
    private javax.swing.JComboBox jcbSolicitante;
    private javax.swing.JLabel jlNumSolicitud;
    private javax.swing.JList jlbDetalleProducto;
    private javax.swing.JPanel jpDetalles;
    private javax.swing.JPanel jpProductosDisponibles;
    private javax.swing.JPanel jpSolicitante;
    private javax.swing.JTextArea jtaObservacion;
    private javax.swing.JTable jtblProductos;
    private javax.swing.JTable jtblResumenProducto;
    private javax.swing.JTextField jtfNombreProducto;
    // End of variables declaration//GEN-END:variables
}
